import { getToken, setToken, removeToken } from '@/utils/auth'
import { getPermission } from '@/api/login'
const user = {
  state: {
    token: getToken(),
    userInfo:null
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_USER_INFO: (state, userInfo) => {
      state.userInfo = userInfo
    },
  },

  actions: {
    // 登录
    Login({ commit }, token) {
      return new Promise((resolve, reject) => {
        setToken(token)
        commit('SET_TOKEN', token)
        resolve()
      })
    },

    // 退出系统
    LogOut({ commit }) {
      commit('SET_TOKEN', '')
      commit('SET_USER_INFO', '')
      removeToken()
    },

    //获取用户信息
    GetUserInfo({ commit }){
      return new Promise((resolve, reject) => {
        getPermission().then(res=>{
          if(res.data){
            commit('SET_USER_INFO', res.data)
            resolve()
          }else{
            reject(new Error('无效的会话，或者会话已过期，请重新登录。'))
          }
        }).catch(error=>{
          reject(error)
        })
      })
      
    }
  }
}

export default user
